#include "opt.h"

int opt_parse(OPT_T* opt, int size, int argc, char** argv)
{
    int i = 0, j = 0, n = 0;

    for (i = 0; i < argc; i++) {
        for (j = 0; j < size / sizeof(OPT_T); j++) {
            if (!strcmp(argv[i], "?") || !strcmp(argv[i], "-h")) {
                for (n = 0; n < size / sizeof(OPT_T); n++) {
                    printf("%s\t%s\n", opt[n].optstr, opt[n].comment);
                }
                return -1;
            }
            if (!strcmp(argv[i], opt[j].optstr)) {
                switch (opt[j].type) {
                case OPT_INT:
                    if ((i + 1) == argc) {
                        fprintf(stderr, "Warn: %s need argument\n", argv[i]);
                        return -1;
                    }
                    if (argv[i + 1][0] < '0' || argv[i + 1][0] > '9') {
                        fprintf(stderr, "Warn: %s need interger argument\n", argv[i]);
                        return -1;
                    }
                    *(int*)opt[j].val = atoi(argv[i + 1]);
                    break;
                case OPT_STRING:
                    if ((i + 1) == argc) {
                        fprintf(stderr, "Warn: %s need argument\n", argv[i]);
                        return -1;
                    }
                    strcpy((char*)opt[j].val, argv[i + 1]);
                    break;
                case OPT_NONE:
                    *(int*)opt[j].val = 1;
                    break;
                }
            }
        }
    }
    return 1;
}